package com.TeacherInfoServer.common.service.Impl;

import com.TeacherInfoServer.common.Result;
import com.TeacherInfoServer.converter.TitleLevelConverter;
import com.TeacherInfoServer.converter.WhetherConverter;
import com.TeacherInfoServer.pojo.DTO.SearchDTO.TitleHistorySearchDTO;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.exception.JobNumberNotExistException;
import com.TeacherInfoServer.mapper.TitleHistoryMapper;
import com.TeacherInfoServer.pojo.entity.TitleHistory;
import com.TeacherInfoServer.pojo.DTO.AddTitleHistoryDTO;
import com.TeacherInfoServer.pojo.DTO.UpdateTitleHistoryDTO;
import com.TeacherInfoServer.pojo.vo.TitleHistoryListVo;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TitleHistoryService;
import com.TeacherInfoServer.pojo.vo.TitleHistoryVo;
import com.TeacherInfoServer.utils.HttpServletUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TitleHistoryServiceImpl extends ServiceImpl<TitleHistoryMapper, TitleHistory> implements TitleHistoryService {

    @Autowired
    private TitleHistoryMapper titleHistoryMapper;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private TitleLevelConverter titleLevelConverter;
    @Autowired
    private WhetherConverter whetherConverter;
    @Override
    @Transactional
    public Result<Map<String, Integer>> addOne(AddTitleHistoryDTO addTitleHistoryDTO) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        Teacher teacher = teacherService.getOne(wrapper.eq(Teacher::getTeacherId,addTitleHistoryDTO.getTeacherId()));
        if (teacher != null){
            String isCurrentTitle;
            if (titleLevelConverter.convertToExcelData(teacher.getJobTitleId()).equals(addTitleHistoryDTO.getTitleLevel())){
                isCurrentTitle = "是";
            } else {
                isCurrentTitle = "否";
            }
            TitleHistory titleHistory =
                    new TitleHistory(null,
                            addTitleHistoryDTO.getTeacherId(),
                            titleLevelConverter.convertToJavaData(addTitleHistoryDTO.getTitleLevel()),
                            addTitleHistoryDTO.getObtainDate(),
                            whetherConverter.convertToJavaData(isCurrentTitle),1,null);
            Integer record = titleHistoryMapper.insert(titleHistory);
            Map<String,Integer> map = new HashMap<>();
            map.put("record",record);
            return Result.success(map);
        } else {
            throw new JobNumberNotExistException();
        }
    }

    @Override
    @Transactional
    public Result<TitleHistoryListVo> getList(Long pageNumber, Long pageSize) {
        Page<TitleHistory> page = new Page<>(pageNumber,pageSize);
        List<TitleHistory> titleHistoryList = titleHistoryMapper.selectPageWithTeacher(page);
        List<TitleHistoryVo> titleHistoryVoList = getTitleHistoryVoList(titleHistoryList);
        TitleHistoryListVo titleHistoryListVo =
                new TitleHistoryListVo(page.getCurrent(),
                        page.getSize(),
                        page.getPages(),
                        page.getTotal(),
                        titleHistoryVoList);
        return Result.success(titleHistoryListVo);
    }
    @Override
    public Map<String,Object> searchTitleHistoryList(TitleHistorySearchDTO titleHistorySearchDTO) {
        if(titleHistorySearchDTO.getIsCurrentTitle()!=null&&!titleHistorySearchDTO.getIsCurrentTitle().isEmpty()&&!titleHistorySearchDTO.getIsCurrentTitle().isBlank()) {
            titleHistorySearchDTO.setIsCurrentTitle(whetherConverter.convertToJavaData(titleHistorySearchDTO.getIsCurrentTitle()).toString());
        }
        Page<?> page = new Page<>(titleHistorySearchDTO.getPages(), titleHistorySearchDTO.getSize());
        titleHistoryMapper.searchTitleHistoryList(page, titleHistorySearchDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("totals", page.getTotal());
        data.put("currentPages", page.getCurrent());
        data.put("pageNumber", page.getPages());
        data.put("rows", page.getRecords());
        return data;
    }

    @Override
    @Transactional
    public Result<TitleHistoryListVo> getOneList(Long pageNumber, Long pageSize, String teacherId) {
        Page<TitleHistory> page = new Page<>(pageNumber,pageSize);
        LambdaQueryWrapper<TitleHistory> wrapper = new LambdaQueryWrapper<>();
        List<TitleHistory> titleHistoryList = titleHistoryMapper.selectPage(page,wrapper.eq(TitleHistory::getTeacherId,teacherId).orderByDesc(TitleHistory::getTitleLevelId)).getRecords();
        List<TitleHistoryVo> titleHistoryVoList = getTitleHistoryVoList(titleHistoryList);
        TitleHistoryListVo titleHistoryListVo =
                new TitleHistoryListVo(page.getCurrent(),
                        page.getSize(),
                        page.getPages(),
                        page.getTotal(),
                        titleHistoryVoList);
        return Result.success(titleHistoryListVo);
    }

    @Override
    public void export(HttpServletResponse response, String fileName) throws IOException {
        HttpServletUtil.setExportResponse(response,fileName);
        List<TitleHistory> titleHistoryList = titleHistoryMapper.selectPageWithTeacher(null);
        List<TitleHistoryVo> titleHistoryVoList = getTitleHistoryVoList(titleHistoryList);
        EasyExcel.write(response.getOutputStream(), TitleHistoryVo.class).excelType(ExcelTypeEnum.XLSX).sheet("Sheet1").doWrite(titleHistoryVoList);
    }

    @Override
    @Transactional
    public Result<Map<String, Integer>> deleteBatch(Integer[] ids) {
        Integer record = titleHistoryMapper.deleteBatchIds(Arrays.asList(ids));
        Map<String, Integer> map = new HashMap<>();
        map.put("record", record);
        return Result.success(map);
    }

    @Override
    @Transactional
    public Result<Map<String, Integer>> updateOne(UpdateTitleHistoryDTO updateTitleHistoryDTO) {
        LambdaQueryWrapper<Teacher> teacherWrapper = new LambdaQueryWrapper<>();
        Teacher teacher = teacherService.getOne(teacherWrapper.eq(Teacher::getTeacherId,updateTitleHistoryDTO.getTeacherId()));
        if (teacher != null){
            String isCurrentTitle;
            if (titleLevelConverter.convertToExcelData(teacher.getJobTitleId()).equals(updateTitleHistoryDTO.getTitleLevel())){
                isCurrentTitle = "是";
            } else {
                isCurrentTitle = "否";
            }
            LambdaUpdateWrapper<TitleHistory> titleHistoryWrapper = new LambdaUpdateWrapper<>();
            Integer record = titleHistoryMapper.update(null,titleHistoryWrapper.eq(TitleHistory::getId,updateTitleHistoryDTO.getId())
                    .set(TitleHistory::getTeacherId,updateTitleHistoryDTO.getTeacherId())
                    .set(TitleHistory::getTitleLevelId,titleLevelConverter.convertToJavaData(updateTitleHistoryDTO.getTitleLevel()))
                    .set(TitleHistory::getObtainDate,updateTitleHistoryDTO.getObtainDate())
                    .set(TitleHistory::getIsCurrentTitle,whetherConverter.convertToJavaData(isCurrentTitle)));
            Map<String, Integer> map = new HashMap<>();
            map.put("record", record);
            return Result.success(map);
        } else {
            throw new JobNumberNotExistException();
        }
    }

    private List<TitleHistoryVo> getTitleHistoryVoList(List<TitleHistory> titleHistoryList){
        return titleHistoryList.stream()
                .map(titleHistory -> new TitleHistoryVo(
                        titleHistory.getId(),
                        titleHistory.getTeacherId(),
                        titleHistory.getTeacher().getTeacherName(),
                        titleLevelConverter.convertToExcelData(titleHistory.getTitleLevelId()),
                        titleHistory.getObtainDate(),
                        whetherConverter.convertToExcelData(titleHistory.getIsCurrentTitle())
                ))
                .collect(Collectors.toList());
    }

}
